package com.ita.acmsystem.merchant.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ita.acmsystem.merchant.entity.Foods;
import com.ita.acmsystem.merchant.entity.Merchant;
import com.ita.acmsystem.merchant.service.IFoodService;
import com.ita.acmsystem.merchant.service.impl.FoodServiceImpl;

/**
 * Servlet implementation class AddFoodsServlet
 */
public class AddFoodsServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private IFoodService foodService = new FoodServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddFoodsServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		add(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		add(request, response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		String foodId = null, foodName = null, foodPrice = null, foodFoodType = null, foodPic = null, merchantId = null;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			

			List<FileItem> items = null;
			try {
				items = upload.parseRequest(request);
				Iterator<FileItem> itor = items.iterator();
				while (itor.hasNext()) {
					FileItem item = itor.next();
					if (item.isFormField()) {
						System.out.println(item.getFieldName() + ":"
								+ item.getString());
						switch (item.getFieldName()) {
						case "foodId":
							foodId = item.getString();
							break;
						case "foodName":
							foodName = item.getString("UTF-8");
							break;
						case "foodPrice":
							foodPrice = item.getString();
							break;
						case "foodFoodType":
							foodFoodType = item.getString();
							break;
						default:
							break;
						}
					} else {
						// TODO
						// upload image
						System.out.println("file size:" + item.getSize());
						System.out.println("file name:" + item.getFieldName());
						System.out
								.println("file type:" + item.getContentType());
						String fileName = UUID.randomUUID() + ".jpg";
						File file = new File(request.getSession()
								.getServletContext().getRealPath("/")
								+ "foodpic\\" + fileName);
						// System.out.println(file.getAbsolutePath());
						// foodPic = "http://localhost:8880/foodpic/" +
						// fileName;

						// read host and port from property.propertties
						InputStream is = AddFoodsServlet.class
								.getClassLoader().getResourceAsStream(
										"property.propertties");
						Properties prop = new Properties();
						prop.load(is);
						String host = prop.getProperty("host");
						String port = prop.getProperty("port");

						foodPic = "http://" + host + ":" + port + "/foodpic/"
								+ fileName;
						// System.out.println(foodPic);
						item.write(file);
					}
				}
				HttpSession session = request.getSession();
				Merchant merchant = (Merchant) session.getAttribute("user");
				merchantId = merchant.getMerchantId();
				// merchantId = "2334";
				if (merchantId == null || "".equals(merchantId)) {
					merchantId = "merchant id is null or blank.";
				}
				Foods food = new Foods(foodId, foodName, foodPrice, foodPic,
						foodFoodType, merchantId);
				PrintWriter writer = response.getWriter();
				if (foodService.addFoods(food)) {
					response.sendRedirect("ContentServlet");
				} else {
					writer.write("<h1>Sorry! Update Fail!</h1>");
				}
				writer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
